Traffic Light is a Mealy Machine. In this case we want the traffic light to have the following behaviour.

Road A Road B Time (s) State
Green Red 8 S0
Yellow Red 3 S1
Red Green 10 S2
Red Yellow 3 S3

State Diagram

traffic light state diagram.png


Block Diagram

mearly machine.png


Verilog Implementation

Traffic Light Module

module Traffic_Light(clk, reset, LightA, LightB);
input clk, reset;
output [2:0] LightA, LightB;

reg [3:0] ncount, ccount;
reg [2:0] LightA, LightB;
reg [1:0] cs,ns;
/*
ccount is the value of count at the current clock
ncount is the value of count at the next clock
cs is current state
ns is next state
*/

//Next State Combinational Logic
always @(*) begin
	case(cs):
	2'b00:
	begin
		ncount = (ccount < 4'd8) ? ccount + 4'd1 :4'd1;
		ns = (ccount < 4'd8) ? 2'b00 : 2'b01;
	end
	2'b01:
	begin
		ncount = (ccount < 4'd3) ? ccount + 4'd1 :4'd1;
		ns = (ccount < 4'd3) ? 2'b01 : 2'b10;
	end
	2'b10:
	begin
		ncount = (ccount < 4'd10) ? ccount + 4'd1 :4'd1;
		ns = (ccount < 4'd10) ? 2'b10 : 2'b11;
	end
	2'b11:
	begin
		ncount = (ccount < 4'd3) ? ccount + 4'd1 :4'd1;
		ns = (ccount < 4'd3) ? 2'b11 : 2'b00;
	endcase
end
// Note that during reset the clock is reseted to 4'd1 this is because, it will take one clock to store the data into the flip-flop.

//State register
always @(posedge clk or negedge reset)begin
	if (!reset) begin
		ccount <= 4'd1;
		cs <= 2'b00;
	end
	else begin
		ccount <= ncount;
		cs <= ns;
	end
end

//Output Combinational Logic
always @(*) begin
	case(cs)
		2'b00:
		begin
			LightA = 001;
			LightB = 100;
		end
		2'b01:
		begin
			LightA = 010;
			LightB = 100;
		end
		2'b10:
		begin
			LightA = 100;
			LightB = 001;
		end
		2'b11:
		begin
			LightA = 100;
			LightB = 010;
		end
	endcase
end

Traffic Light with Frequency Divider

To let the traffic light works as intended we will need a 1Hz clock, as such Frequency Divider is needed.

module TL_ACC(clk, w_en, reset, Acc_out);
input clk, reset;
output [2:0] LightA, LightB;

wire clk_ls

FDiv F0(.Fin(clk),.Fsel(3'b011),.Fout(clk_ls));
Traffic_Light TL0(.clk(clk_ls), .reset(reset), .LightA(LightA), .LightB(LightB))

endmodule